package com.travel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.travel.entity.po.UserArticle;
import com.travel.mapper.UserArticleMapper;
import com.travel.service.UserArticleService;
import com.travel.utils.Base64ToImg;
import com.travel.utils.Base64ToImgNew;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Author:Jasenon_ce
 * Date: 2025.04.19/下午4:36
 */
@Service
public class UserArticleServiceImpl implements UserArticleService {

    @Autowired
    private UserArticleMapper userArticleMapper;

    @Autowired
    Base64ToImgNew base64ToImgNew;



    @Override
    public void insert(UserArticle userArticle) {
        userArticle.setRichContent(base64ToImgNew.richtextBase64ToImg(userArticle.getRichContent()));
        userArticleMapper.insert(userArticle);
    }

    @Override
    public boolean delete(Long articleId, Long username) {
        QueryWrapper<UserArticle> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleId);
        wrapper.eq("username", username);

        if (userArticleMapper.selectCount(wrapper) != 1) return false;
        userArticleMapper.delete(wrapper);
        return true;
    }

    @Override
    public synchronized void like(Long articleId) {
        QueryWrapper<UserArticle> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleId);

        UserArticle userArticle = userArticleMapper.selectOne(wrapper);
        if (userArticle == null) return;

        userArticle.setLikeCount(userArticle.getLikeCount()+1);
        userArticleMapper.updateById(userArticle);
    }

    @Override
    public void top(Long articleId, Boolean istop) {

        QueryWrapper<UserArticle> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleId);

        UserArticle userArticle = userArticleMapper.selectOne(wrapper);
        if (userArticle == null) return;

        userArticle.setTop(istop);
        userArticleMapper.updateById(userArticle);
    }


}
